package com.atguigu.gulimall.ssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;


import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @DESCRIPTION: 单点登录 客户端控制器
 * @author: zr
 * @DATE: 2023/1/14 20:45
 */
@Controller
public class HelloController {

    @Value("${sso.server.url}")
    private String ssoServerUrl;

    /**
     * 无需登录即可
     *
     * @return
     */
    @GetMapping("/hello")
    @ResponseBody
    public String hello() {
        return "hello";
    }

    /**
     *
     * @param model
     * @param session
     * @param token 有token代表已经登录
     * @return
     */
    @GetMapping("/boss")
    public String employees(Model model, HttpSession session, @RequestParam(required = false) String token) {
       if (!StringUtils.isEmpty(token)){
           RestTemplate restTemplate=new RestTemplate();
           ResponseEntity<String> entity = restTemplate.getForEntity("http://ssoserver.com:8080/userInfo?token=" + token, String.class);
           String body = entity.getBody();
           session.setAttribute("loginUser",body);
       }
        Object loginUser = session.getAttribute("loginUser");
        // 判断是否登录
        if (loginUser == null) {
            // 没有登录 跳转到登录服务器进行登录
            // 使用url上的查询参数 作为标识自己是哪个页面
            return "redirect:" + ssoServerUrl + "?redirect_url=http://client2.com:8082/boss";
        } else {
            List<String> emps = new ArrayList<>();
            emps.add("张三");
            emps.add("李四");
            model.addAttribute("emps", emps);
            return "list";
        }
    }
}
